package com.xckj.cycling.utils

import android.content.Intent
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.FacebookSdk
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.xckj.cycling.context.AppContext
import com.xckj.cycling.framework.BaseActivityKt


/**
 * faceBook登录
 */
class FacebookLoginUtils(activity: BaseActivityKt) : BaseLoginUtil(activity) {
    private val facebookCallBack: CallbackManager = CallbackManager.Factory.create()

    companion object {
        init {
            FacebookSdk.sdkInitialize(AppContext.globalContext())
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        facebookCallBack.onActivityResult(requestCode, resultCode, data)
    }

    override fun startLogin() {
        LoginManager.getInstance()
            .registerCallback(facebookCallBack, object : FacebookCallback<LoginResult> {
                override fun onSuccess(loginResult: LoginResult) {
                    if (loginResult == null) {
                        onError(FacebookException("result is null"))
                    } else {
                        viewModel.loginByFacebook(loginResult) {
                            if (!it.isSuccessful) {
                                activity.showMessage(it.msg)
                            }
                            activity.hideDialog()
                        }
                    }
                }

                override fun onCancel() {
                    onError(FacebookException("called cancel"))
                }

                override fun onError(error: FacebookException) {
                    activity.hideDialog()
                    activity.showMessage(error.message)
                    error.printStackTrace()
                }
            })
        LoginManager.getInstance().logIn(activity, listOf("public_profile", "email"))
    }

    override fun onDestroy() {
        LoginManager.getInstance().unregisterCallback(facebookCallBack)
    }

}